package com.hand.app.service.impl;

import com.hand.app.service.SoLineService;
import com.hand.domain.content.OrderStatus;
import com.hand.domain.entity.SoHeader;
import com.hand.domain.entity.SoLine;
import com.hand.domain.repository.SoHeaderRepository;
import com.hand.domain.repository.SoLineRepository;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 订单表应用服务默认实现
 */
@Service
public class SoLineServiceImpl implements SoLineService {

    @Resource
    private SoLineRepository soLineRepository;
    @Resource
    private SoHeaderRepository soHeaderRepository;

    /**
     * 订单行删除API
     * @param soLineId
     */
    @Override
    public void deleteOrderHeader(Long soLineId) {

        SoLine soLine_exist = soLineRepository.selectByPrimaryKey(soLineId);
        if (soLine_exist == null){
            throw new CommonException("单据不存在！");
        }
        if (!soLine_exist.getCreatedBy().equals(DetailsHelper.getUserDetails().getUserId())){
            throw new CommonException("您和单据创建者身份不一致！");
        }
        SoHeader soHeader = soHeaderRepository.selectByPrimaryKey(soLine_exist.getSoHeaderId());
        if (!OrderStatus.NEW.equals(soHeader.getOrderStatus()) && !OrderStatus.REJECTED.equals(soHeader.getOrderStatus())){
            throw new CommonException("单据状态不为NEW 或 REJECTED！");
        }
        soLineRepository.deleteByPrimaryKey(soLine_exist.getSoLineId());
    }
}
